package com.hongye.proprietary.controller;

import com.hongye.common.utils.R;
import com.hongye.proprietary.controller.vo.SmsVerificationCodeVo;
import com.hongye.proprietary.utils.VerifyImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/proprietary/util")
public class SlideController {
    @Autowired
    private AgentUserController agentUserController;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private SmsVerificationCodeVo smsVerificationCodeVo;


    /**
     * 跳转到图片验证界面
     * @return 图片验证界面
     */
    @RequestMapping("imgValida")
    public String toImgValidate(Model model, String telephone, HttpServletResponse response){
                smsVerificationCodeVo.setTelephone(telephone);
                model.addAttribute("telephone",telephone);
                return "imageValidate";
    }

     //图片加载 实现
    @RequestMapping("createImgValidate")
    @ResponseBody
    public R createImgValidate(SmsVerificationCodeVo vo){
        try {
            Integer templateNum = new Random().nextInt(4) + 1;
            Integer targetNum = new Random().nextInt(20) + 1;
            File templateFile = ResourceUtils.getFile("classpath:static/images/validate/template/"+templateNum+".png");
            File targetFile = ResourceUtils.getFile("classpath:static/images/validate/target/"+targetNum+".jpg");
            Map<String, byte[]> pictureMap =  VerifyImageUtil.pictureTemplatesCut(templateFile, targetFile,
                    "png","jpg");
            // 将生成的偏移位置信息设置到redis中
            String key = "WEB_VALID_IMAGE_PREFIX"+ vo.getTelephone();
            //boolean verified = redisUtil.exists(key);
            Boolean verified = redisTemplate.hasKey(key);
            if(verified){
                redisTemplate.delete(key);
            }
            redisTemplate.opsForValue().set(key,(VerifyImageUtil.getX()+67)+"",60, TimeUnit.SECONDS);
            return R.ok().put("data",pictureMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(4000,"处理图片失败");
        }
    }


    //滑动锁校验
    @RequestMapping("checkImgValidate")
    @ResponseBody
    public R checkImgValidate(SmsVerificationCodeVo vo){
        if(Objects.nonNull(vo)){
            String key = generateKeyByTelephone(vo);
            boolean verified = redisTemplate.hasKey(key);
            int offsetHorizontalSystem = Integer.parseInt(redisTemplate.opsForValue().get(key));
            int difference = Math.abs(offsetHorizontalSystem-vo.getOffsetHorizontal());
            if(difference <= 10){
                //验证码通过
                redisTemplate.delete(key);
                //存入redis60s
                redisTemplate.opsForValue().set(key,offsetHorizontalSystem+"",60,TimeUnit.SECONDS);
                //调用发短信
                R r = agentUserController.sendMsg(smsVerificationCodeVo.getTelephone());
                return R.ok(r);
            }
        }

        return R.error("验证未通过");
    }
    /**
     * 根据手机号生成图片验证码key
     * @param vo 手机号信息
     * @return 验证码key
     */
    private String generateKeyByTelephone(SmsVerificationCodeVo vo){
        String key = "";
        if(!StringUtils.isEmpty(vo.getTelephone())){
            key = "WEB_VALID_IMAGE_PREFIX" + vo.getTelephone();
        }else if(!StringUtils.isEmpty(vo.getAccount())){
        }
        return key;
    }
}
